package com.cloudspace.jindun.message;

import android.content.Context;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.error.VolleyError;
import com.cloudspace.jindun.JindunApp;
import com.cloudspace.jindun.R;
import com.cloudspace.jindun.constants.Constants;
import com.cloudspace.jindun.global.Res;
import com.cloudspace.jindun.log.APPLog;
import com.cloudspace.jindun.model.NoticeMessageResult;
import com.cloudspace.jindun.network.api.API;
import com.cloudspace.jindun.network.base.ApiCallback;
import com.cloudspace.jindun.user.UserSessionManager;
import com.cloudspace.jindun.utils.AppPreferences;

import org.apache.http.HttpStatus;

import io.rong.imkit.model.ProviderTag;
import io.rong.imkit.model.UIMessage;
import io.rong.imkit.widget.provider.IContainerItemProvider;
import io.rong.imlib.model.Message;

/**
 * Created by zengxianhua on 17/3/21.
 */

@ProviderTag(messageContent = InfoMessage.class)
public class InfoMessageItemProvider extends IContainerItemProvider.MessageProvider<InfoMessage> {
    private static final String TAG = InfoMessageItemProvider.class.getSimpleName();

    class ViewHolder {
        TextView content_tv;
        TextView read_tv;
        ImageView receive_iv;
        LinearLayout sender_ll;
    }

    @Override
    public View newView(Context context, ViewGroup group) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_info_message, null);
        ViewHolder holder = new ViewHolder();

        holder.content_tv = (TextView) view.findViewById(R.id.content_tv);
        holder.read_tv = (TextView) view.findViewById(R.id.read_tv);
        holder.receive_iv = (ImageView) view.findViewById(R.id.receive_iv);
        holder.sender_ll = (LinearLayout) view.findViewById(R.id.send_ll);

        view.setTag(holder);
        return view;
    }



    @Override
    public void bindView(View view, int i, InfoMessage infoMessage, UIMessage uiMessage) {
        ViewHolder holder = (ViewHolder) view.getTag();

        infoMessage.id = String.valueOf(uiMessage.getMessage().getSentTime());
        infoMessage.groupId = String.valueOf(uiMessage.getMessage().getTargetId());

        boolean hasRead = AppPreferences.getBoolean(getNoticeReadKey(infoMessage, false), false);
        int remainNumber = AppPreferences.getInt(getNoticeReadKey(infoMessage, true), 0);

        APPLog.zxhLog(TAG + "notice_read key " + getNoticeReadKey(infoMessage, true) + " number:" + remainNumber);

        if (remainNumber != 0){
            infoMessage.read = String.format(Res.getString(R.string.notice_unread_count),
                    remainNumber);
        }


        boolean isMeSend = (uiMessage.getMessageDirection() == Message.MessageDirection.SEND);
        if (isMeSend){
            holder.read_tv.setVisibility(View.VISIBLE);
            openNotice(infoMessage);
        }else{
            holder.read_tv.setVisibility(View.GONE);
        }

        if (isMeSend || hasRead) {//消息方向，自己发送的或是已读的
            inSenderMode(infoMessage, holder);
        } else {
            holder.sender_ll.setVisibility(View.GONE);
            holder.receive_iv.setVisibility(View.VISIBLE);
        }
    }

    private void inSenderMode(InfoMessage infoMessage, ViewHolder holder) {
        //发请求更新
        holder.sender_ll.setVisibility(View.VISIBLE);
        holder.receive_iv.setVisibility(View.GONE);

        holder.content_tv.setText(infoMessage.content);

        if (!TextUtils.isEmpty(infoMessage.read)){
            holder.read_tv.setText(infoMessage.read);
        }
    }

    @Override
    public Spannable getContentSummary(InfoMessage data) {
        return new SpannableString("这是一条自定义消息InfoMessage");
    }

    @Override
    public void onItemClick(View view, int i, InfoMessage infoMessage, UIMessage uiMessage) {
        boolean isMeSend = (uiMessage.getMessageDirection() == Message.MessageDirection.SEND);
        if (!isMeSend){
            openNotice(infoMessage);
        }

        if (uiMessage.getMessageDirection() == Message.MessageDirection.RECEIVE
                && (view.getTag() instanceof ViewHolder)
                ){
            inSenderMode( infoMessage, (ViewHolder) view.getTag());

            APPLog.zxhLog(TAG + " read message:" + infoMessage.id);
            AppPreferences.putBoolean(getNoticeReadKey(infoMessage, false), true);
        }else{
            gotoNoticeDetailPage(infoMessage);
        }

    }

    private String getNoticeReadKey(InfoMessage message, boolean readKey){
        String tag = readKey ? Constants.GROUP_CHAT_MESSAGE_READ_NUMBER : Constants.GROUP_CHAT_MESSAGE_ID;
        String key = String.format("%s_%s_%s", tag, message.id, message.groupId);
        return key;
    }


    private void openNotice(final InfoMessage infoMessage) {
        APPLog.zxhLog(TAG + " openNotice:" + infoMessage.id);

        API.getInstance().getNoticeApi().openNotification(TAG,
                infoMessage.id, UserSessionManager.getInstance().getUserId(), infoMessage.groupId,
                new ApiCallback<NoticeMessageResult>() {
                    @Override
                    public void handleResult(NoticeMessageResult result, VolleyError error) {
                        if (result != null && result.status == HttpStatus.SC_OK){
                            AppPreferences.putBoolean(getNoticeReadKey(infoMessage, false), true);
                        }
                    }
                }.toastActionError());
    }

    private void gotoNoticeDetailPage(InfoMessage infoMessage) {
        NoticeDetailPageActivity.showActivity(JindunApp.getInstance(), infoMessage);
    }

    @Override
    public void onItemLongClick(View view, int i, InfoMessage infoMessage, UIMessage uiMessage) {

    }

}
